package cn.itsource.service.impl;

import cn.itsource.domain.Article;
import cn.itsource.domain.Ip;
import cn.itsource.mapper.ArticleMapper;
import cn.itsource.mapper.IpMapper;
import cn.itsource.query.IpQuery;
import cn.itsource.service.IpService;
import cn.itsource.util.AjaxResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 业务实现类：Ip地址
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
public class IpServiceImpl implements IpService {

    @Autowired
    private IpMapper ipMapper;
    @Autowired
    private ArticleMapper articleMapper;

    @Override
    public List<Ip> findAll() {
        return ipMapper.findAll();
    }

    @Override
    public Ip findOne(Long id) {
        return ipMapper.findOne(id);
    }

    @Transactional
    @Override
    public void add(Ip ip) { //
        ipMapper.add(ip);
    }

    @Transactional
    @Override
    public void update(Ip ip) {
        ipMapper.update(ip);
    }

    @Transactional
    @Override
    public void delete(Long id) {
        ipMapper.delete(id);
    }

    @Override
    public PageInfo<Ip> pageQuery(IpQuery query) {
       /* //查询总条数 - 原生分页的写法
        Integer totals = ipMapper.queryCount();
        //查询当前页的分页数据
        List<Ip> list = ipMapper.queryData(query);*/
        //开启分页：1.首先查询总数量 2.根据驱动名使用相应的方式进行分页查询，如果是mysql，就会用limit 3.自动计算limit的第1个参数
        PageHelper.startPage(query.getCurrentPage(),query.getPageSize());
        List<Ip> list = ipMapper.pageQuery(query);
        return new PageInfo<>(list);
    }

    @Override
    public void patchDel(Long[] ids) {
        ipMapper.patchDel(ids);
    }

    @Override
    public AjaxResult isStar(Ip ip) {
        Ip dbIp = ipMapper.findByArticleId(ip);
        if(dbIp == null){//没有绑定过
            return new AjaxResult(false,"");
        }
        return new AjaxResult();
    }

    @Override
    public AjaxResult starNum(Ip ip) {
        Ip dbIp = ipMapper.findByArticleId(ip);
        Article article = articleMapper.findOne(ip.getArticleId());
        if(dbIp == null){//没点过赞 - 进行点赞
            article.setArticleStarNum(article.getArticleStarNum() + 1);
            articleMapper.update(article);
            ipMapper.add(ip);
            return AjaxResult.me().setObj(article.getArticleStarNum());
        }else{//点过赞了 - 取消点赞
            article.setArticleStarNum(article.getArticleStarNum() - 1);
            articleMapper.update(article);
            ipMapper.delete(dbIp.getId());
            return AjaxResult.me().setSuccess(false).setObj(article.getArticleStarNum());
        }
    }

}
